<template>
	<div  class="margin-tb-xs">
		<button  class="css-1p3hq3p ant-btn ant-btn-primary" type="button"
		 @click="getCommentPage"
		>
			<!--@click="router.push(`/course/onlineStudy/${courseId}`)"-->
			<span>去发表评论</span>
		</button>
	</div>
  <div class="remarks-analyse-box">
	
    <div class="remarks-analyse-goods">
      好评率: {{ applauseRate }}%
    </div>
  </div>
  <div class="remarks-bar">
            <span @click="viewByGrade('')" :class="{selectedBar: pageInfo.grade === ''}">全部({{
                commentTypeNum.all
              }})</span>
    <span @click="viewByGrade('1')"
          :class="{selectedBar: pageInfo.grade === '1'}">好评({{ commentTypeNum.good }})</span>
    <span @click="viewByGrade('2')" :class="{selectedBar: pageInfo.grade === '2'}">中评({{
        commentTypeNum.moderate
      }})</span>
    <span @click="viewByGrade('3')"
          :class="{selectedBar: pageInfo.grade === '3'}">差评({{ commentTypeNum.worse }})</span>
  </div>
  <a-spin :spinning="loading">
    <a-comment v-for="(item,index) in commentList" :key="index" v-if="commentList?.length > 0">
      <template #actions>
        <span key="comment-nested-reply-to" @click="currentReplay(item)">回复</span>
        <span @click="deleteComment(item)" v-if="userInfo.id == item.userId">删除</span>
      </template>
      <template #author>
        <a>{{ item.realname }}</a>
      </template>
      <template #avatar>
        <a-avatar :src="getFileAccessHttpUrl(item.avatar)" />
      </template>
      <template #datetime>
        <span class="title"> {{ getTimeDiff(item.createTime) }}</span>
      </template>
      <template #content>
        <div class="remarks-content-box">
          <p>
            <a-rate v-model:value="item.ceScore" allow-half disabled />
          </p>
          <p class="remarks-content">{{ item.commentContent }}</p>
          <div class="comment-img" v-if="item.images">
            <div v-for="(img, imgIndex) in item.images.split(',')" :key="imgIndex">
              <a-image :src="getFileAccessHttpUrl(img)" :width="100" />
            </div>
          </div>
        </div>
      </template>
      <template v-if="item?.childCommentList?.length > 0">
        <a-comment v-for="(child,childIndex) in item.childCommentList" :key="childIndex">
          <template #actions>
            <span @click="currentReplay(child)">回复</span>
            <span @click="deleteComment(child)" v-if="userInfo.id == child.userId">删除</span>
          </template>
          <template #author>
            <a>{{ child.realname }}</a>
            <template v-if="child.replyName">
              <span style="margin: 0 10px">回复</span>
              <span>{{ child.replyName }}</span>
            </template>
          </template>
          <template #avatar>
            <a-avatar :src="getFileAccessHttpUrl(child.avatar)" />
          </template>
          <template #datetime>
            <span class="title"> {{ getTimeDiff(child.createTime) }}</span>
          </template>
          <template #content>
            <p>
              {{ child.content }}
            </p>
          </template>
        </a-comment>
      </template>
    </a-comment>
    <a-empty v-else description="暂无评论！" />
    <Pagination :pageNo="pageInfo.pageNo" :pageSize="pageInfo.pageSize" :total="total"
                @change-page="changePage" style="margin-top: 20px" />
  </a-spin>
  <a-modal v-model:open="showComment" title="我要评论" width="600px" :footer="null"
           destroy-on-close>
    <a-row>
      <a-col :span="24">
        <a-textarea :rows="5" v-model:value="commentContent" />
      </a-col>
    </a-row>
    <a-row style="margin-top: 10px">
      <a-col :span="4" :offset="20">
        <a-button type="primary" danger @click="replayTo">发布评论</a-button>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script lang="ts" setup>
import { countGradeNumber, listGoodsEvaluation,apiCommitComment ,apiGetCommentList} from "@/api/course";
import { addEvaluationReply, deleteEvaluation } from "@/api/order";

import { onMounted, reactive, ref } from "vue";
import { getFileAccessHttpUrl } from "@/utils/compUtils";
import { useMessage } from "@/hooks/web/useMessage";
import { getTimeDiff } from "@/utils";
import Pagination from "@/components/Pagination.vue";
import { formatToDateTime } from "@/utils/dateUtil";
import { useWebStore } from "@/store";
import { useRoute,useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const commentContent = ref<any>();
const currentComment = ref<any>();
const showComment = ref<boolean>(false);
const applauseRate: any = ref<number>(0);
const { createMessage, createConfirm } = useMessage();
const loading = ref<boolean>(false);
const total = ref<number>(0);
const commentList = ref<any>([]); // 根评论列表
const allCommentList = ref<any>([]); //所有评论
const gradeNumberList = ref<any>([]);
const webStore = useWebStore();
const userInfo = ref<any>({});
const courseId = route.params?.id ?? -1;
const props = defineProps({
  course: {
    type: Object,
    default: {}
  }
});
const pageInfo = reactive({ // 评论传参
  pageNo: 1,
  pageSize: 10,
  grade: "",
  courseId: ""
});
const commentTypeNum = reactive<any>({
  all: 0,
  good: 0,
  moderate: 0,
  worse: 0
}); // 评论数量，包括好中差分别的数量

function changePage(pageNo) {
  pageInfo.pageNo = pageNo;
  getCommentList();
}

async function getCommentList() { // 获取评论列表
  loading.value = true;
  
  pageInfo.courseId = courseId;
  console.log("分页信息：",pageInfo.courseId)
  const data: any = await apiGetCommentList(pageInfo);
  allCommentList.value = data.result?.records;
  console.log("data:",data)
  commentList.value = data.result?.records.filter(val => !val.parentId);
  commentList.value.forEach(comment => {
    comment.childCommentList = allCommentList.value.filter(val => val.parentId == comment.id);
  });
  total.value = data.result?.total;
  loading.value = false;
}

async function listGradeNumber() {
  const data: any = await countGradeNumber(props.course?.id);
  gradeNumberList.value = data?.result;
  let goodNum = 0;
  let moderateNum = 0;
  let worseNum = 0;
  gradeNumberList.value.forEach((item: any) => {
    if (item.grade == 1) {
      goodNum += item.number;
    }
    if (item.grade == 2) {
      moderateNum += item.number;
    }
    if (item.grade == 3) {
      worseNum += item.number;
    }
  });
  commentTypeNum.good = goodNum;
  commentTypeNum.moderate = moderateNum;
  commentTypeNum.worse = worseNum;
  commentTypeNum.all = goodNum + moderateNum + worseNum;
  if (commentTypeNum.all > 0) {
    applauseRate.value = (commentTypeNum.good / commentTypeNum.all * 100).toFixed(1);
  }
}

function viewByGrade(grade) { // 好中差评切换
  pageInfo.pageNo = 1;
  pageInfo.grade = grade;
  getCommentList();
}

function currentReplay(item) {
  currentComment.value = item;
  showComment.value = true;
}

function getCommentPage(){
	router.push("/course/comment/"+courseId);
}
async function replayTo() {
  let params = {
    courseId: courseId,
    parentId: currentComment.value.parentId ?? currentComment.value.id,
    commentContent: commentContent.value,
    isLike: false,
    likeCount: 0,
    createTime: formatToDateTime(new Date()),
    replyId: currentComment.value.id,
    replyUserId: currentComment.value.userId
  };
  await apiCommitComment(params);
  commentContent.value = "";
  showComment.value = false;
  createMessage.success("评论成功");
  getCommentList();
}

async function deleteComment(item) {
  createConfirm({
    iconType: "warning",
    title: "提示",
    content: "确实要删除该评论吗？",
    onOk: async () => {
      await deleteEvaluation(item.id);
      createMessage.success("删除成功");
      getCommentList();
    },
    // 隐藏掉取消按钮
    cancelButtonProps: { style: { display: "none" } }
  });
}

onMounted(() => {
  userInfo.value = webStore.getUserInfo;
  getCommentList();
  listGradeNumber();
});
</script>

<style scoped lang="scss">
@import "@/assets/style/course/global.scss";

.remarks-analyse-box {
  padding: 10px 0;
  display: flex;
  align-items: center;
}

.remarks-analyse-goods {
  margin-right: 15px;
}

.remarks-analyse-num {
  font-size: 26px;
}

.remarks-analyse-title {
  font-size: 12px;
  line-height: 20px;
}

.remarks-bar {
  padding-left: 15px;
  height: 36px;
  line-height: 36px;
  color: #666666;
  background-color: #F7F7F7;

  span:hover {
    cursor: pointer;
  }

  .selectedBar {
    color: $theme_color;
  }
}

.remarks-bar span {
  margin-right: 15px;

}

.remarks-box {
  padding: 15px;
  display: flex;
  flex-direction: row;
  border-bottom: 1px #ccc dotted;
}

.remarks-user-name {
  padding-left: 15px;
}
.css-1p3hq3p{
	color:#ffffff;
	background-color:#1677ff;
	box-shadow:0 2px 0 rgba(5,145,255,1);
	font-size:14px;height:32px;
	padding:4px 15px;
	border-radius:6px;
	outline:none;
	font-weight:400;
	text-align:center;
	cursor:pointer;
}
.remarks-content-box {
  width: calc(100%);
  padding: 10px 30px;

  .comment-img {
    display: flex;

    .borderColor {
      border-color: $theme_color;
    }

    div {
      border: 1px solid #999;
      margin-right: 20px;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.remarks-content {
  font-size: 14px;
  color: #232323;
  line-height: 28px;
}

:deep(.ant-comment-content-detail p) {
  margin-bottom: 10px;
}

</style>
